package com.sapp.imagecolorization.image_settings

import android.content.ContentResolver
import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.provider.MediaStore
import com.sapp.imagecolorization.notification.Notification
import com.squareup.picasso.Picasso
import com.squareup.picasso.Target
import java.lang.ref.WeakReference

open class SaveImageHelper : Target {
    private lateinit var context: Context
    private val notification = Notification()
    private var weakReferenceContentResolver: WeakReference<ContentResolver>
    private var name: String
    private var desc: String

    constructor(context: Context, contentResolver: ContentResolver, name: String, desc: String) {
        this.context = context
        this.weakReferenceContentResolver = WeakReference<ContentResolver>(contentResolver)
        this.name = name
        this.desc = desc
    }

    var notificationId = 0
    override fun onBitmapLoaded(bitmap: Bitmap?, from: Picasso.LoadedFrom?) {
        val contentResolver = weakReferenceContentResolver.get()
        if (contentResolver != null) {
            MediaStore.Images.Media.insertImage(contentResolver, bitmap, name, desc)
            notification.showDownloadingNotification(context, name, notificationId++)
        }

    }

    override fun onBitmapFailed(e: Exception?, errorDrawable: Drawable?) {

    }

    override fun onPrepareLoad(placeHolderDrawable: Drawable?) {

    }

}